package com.lovo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lovo.bean.Savemoney;
import com.lovo.bean.SysUser;
import com.lovo.mapper.SavemoneyMapper;
import com.lovo.service.ISavemoneyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lovo.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lovo
 * @since 2022-09-17
 */
@Service
public class SavemoneyServiceImpl extends ServiceImpl<SavemoneyMapper, Savemoney> implements ISavemoneyService {


    @Autowired
    SavemoneyMapper savemoneyMapper;

    @Autowired
    ISysUserService userService;

    @Override
    public IPage<Savemoney> findSaveMoneyInfoByUserId(Integer PageNO, Integer userId) {
        QueryWrapper<Savemoney> qw = new QueryWrapper<>();
        qw.eq("userId",userId);
        return savemoneyMapper.selectPage(new Page(PageNO,5),qw);
    }

    @Override
    public Boolean updateUserSaveMoneyByUserId(Integer userId, Integer money,String status) {
        Savemoney savemoney = new Savemoney();
        savemoney.setUserid(userId);
        savemoney.setSavestatus(status);
        savemoney.setSavacode((int) System.currentTimeMillis());

        SysUser user = userService.getBaseMapper().selectById(userId);
        if (status.equals("存入")){
            user.setSavemoney(user.getSavemoney()+money);
            savemoney.setSalemoney(money);
            savemoneyMapper.insert(savemoney);
            userService.updateMoneyByUserId(userId,money);
            return true;
        }
        if (status.equals("支出")){
            if (user.getSavemoney() >= money){
                user.setSavemoney(user.getSavemoney() - money);
                savemoney.setSalemoney(money);
                savemoneyMapper.insert(savemoney);
                userService.updateMoneyByUserId(userId,-money);
                return true;
            }
            else{
                return false;
            }
        }

        return false;
    }

}
